package com.jackstraw.jack_base.mq.common.entity;

import com.jackstraw.jack_base.mq.common.entity.enums.DelayMessageLevelEnum;
import com.jackstraw.jack_base.util.ObjectUtil;
import com.jackstraw.jack_base.util.StringUtil;
import com.jackstraw.jack_base.util.tenant.contextholder.TenantContextHolder;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * MQ消息体
 *
 * @param <M>
 */
@Data
@Accessors(chain = true)
public class MqMessage<M> implements Serializable {

    private static final long serialVersionUID = -719617586179111971L;


    public MqMessage() {
        this.getHeaders().put("tenantName", TenantContextHolder.get());
    }

    public MqMessage(String tenantName) {
        this.getHeaders().put("tenantName", tenantName);
    }


    /**
     * 消息发送的主题
     */
    private String topic;

    /**
     * 消息的主键
     */
    private String key;

    /**
     * 消息体
     */
    private M message;

    /**
     * 多条消息
     */
    private Collection<M> messageS;

    /**
     * 超时时间
     */
    private Long timeout;

    /**
     * 定时/延时 消息等级
     */
    private DelayMessageLevelEnum delayMessageLevelEnum;

    /**
     * 要发送的消息的头信息
     * <p>
     * 为给定的头名称设置值。 如果提供的值是{@code null}，头文件将被删除。
     */
    private Map<String, String> headers = new HashMap<>();

    public Map<String, Object> getHeadersByObject() {
        Map<String, Object> headersByObject = new HashMap<>();
        headers.forEach((k, v) -> headersByObject.put(k, v));
        return headersByObject;
    }

    public MqMessage<M> setHeaders(String headerName, String headerValue) {
        if (StringUtil.StringUtilsBylang3.isEmpty(headerValue)) {
            this.getHeaders().remove(headerName);
            return this;
        }
        this.getHeaders().put(headerName, headerValue);
        return this;
    }

    /**
     * 事务ID
     */
    private String transactionId;

    public String getTopic() {
        return StringUtil.StringUtilsBylang3.isEmpty(this.topic) ? "" : this.topic;
    }

    /**
     * 设置消息体
     *
     * @param topic
     * @param message
     */
    public void setMessage(String topic, M message) {
        this.topic = topic;
        this.message = message;
    }

    /**
     * 设置消息体集合
     *
     * @param topic
     * @param messageS
     */
    public void setMessageS(String topic, Collection<M> messageS) {
        this.messageS = messageS;
    }

    public Long getTimeout(Long timeout) {
        return ObjectUtil.ObjectUtilByLang3.isEmpty(this.getTimeout()) ? timeout : this.getTimeout();
    }
}
